
//
//  AppDelegate.m
//  DataStatistics
//
//  Created by Kang on 15/5/22.
//  Copyright (c) 2015年 YTYangK. All rights reserved.
//


#import "AppDelegate.h"
#import "BPush.h"
#import "ControllerTool.h"
#import "SearchVC.h"
#import "WelcomeViewController.h"
#import "DevicesWelcome.h"

#import "TabBarC.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "DeploySDK.h"


#define SUPPORT_IOS8 1
#define _IPHONE80_ 80000
#define STOREAPPID @"1250697093"


@interface AppDelegate () <UIAlertViewDelegate> {
    BOOL isJudge;
    DevicesWelcome *DevicesView;
    
}
@property (strong, nonatomic) DeploySDK  *sdk;
@end

@implementation AppDelegate

//static SystemSoundID shake_sound_male_id = 0;

- (id)init
{
    if (self = [super init]) {
        _isLaunchedByNotification = NO;
        //测试用
        isJudge = YES;
    }
    return self;
}



#pragma mark - application 首次运行
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    //创建窗口
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    [self.window makeKeyAndVisible]; // 显示窗口成为主窗
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"BCD"];
    
    //添加欢迎页
    //    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"isHaveVisit"]) {
    UIStoryboard* main;
    // 判断登陆令牌是否为空
    if (isLogin) { // - YES不是空
        [ControllerTool chooseRootViewController];
        [self.sdk updateSession];
    }else { // - 空
        main = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
        self.window.rootViewController = [main instantiateInitialViewController];
    }
    
    //    }else{
    //        //如果这个if判断，返回的对象为nil
    //        //没有进入过APP
    //        //加载欢迎页
    //        WelcomeViewController *welcome = [[WelcomeViewController alloc]init];
    //        self.window.rootViewController = welcome;
    //
    //    }
    
    [[UISegmentedControl appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] } forState:UIControlStateNormal];
    [[UISegmentedControl appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] } forState:UIControlStateSelected];
    
    // 注册推送
//    [self.sdk registerPushServiceWithApplication:application :launchOptions];
    
    
    [self initBPushSDKWithOptions:launchOptions];
    
    // Mob SMS
    [SMSSDK registerApp:MOBSMSAPPKEY withSecret:MOBSMSAPPSECRET];
    
    // ShareSDK
    //    [self initShareSDK];
    
    // Code Data
    [self setManagedObjectContext:self.managedObjectContext];
    
    //检查app是否有更新
    [self hsUpdateApp];
    
    return YES;
}

//检查app是否有更新
-(void)hsUpdateApp
{
    //2先获取当前工程项目版本号
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
    
    //3从网络获取appStore版本号
    NSError *error;
    NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",STOREAPPID]]] returningResponse:nil error:nil];
    if (response == nil) {
        NSLog(@"你没有连接网络哦");
        return;
    }
    
    NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        NSLog(@"hsUpdateAppError:%@",error);
        return;
    }
    NSArray *array = appInfoDic[@"results"];
    NSDictionary *dic = array[0];
    NSString *appStoreVersion = dic[@"version"];
    //打印版本号
    NSLog(@"当前版本号:%@\n商店版本号:%@",currentVersion,appStoreVersion);
    //4当前版本号小于商店版本号,就更新
    if([currentVersion floatValue] < [appStoreVersion floatValue])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"检测到新版本(%@),是否更新?",appStoreVersion] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新",nil];
        [alert show];
    }else{
        NSLog(@"版本号好像比商店大噢!检测到不需要更新");
    }
    
}

- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //5实现跳转到应用商店进行更新
    if(buttonIndex==1)
    {
        //6此处加入应用在app store的地址，方便用户去更新，一种实现方式如下：
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8", STOREAPPID]];
        [[UIApplication sharedApplication] openURL:url];
    }
}

#pragma mark - 程序暂行
- (void)applicationWillResignActive:(UIApplication*)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

#pragma mark - 程序进入后台
- (void)applicationDidEnterBackground:(UIApplication*)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    //  UIBackgroundTaskIdentifier task = [application beginBackgroundTaskWithExpirationHandler:^{
    // 当申请的后台运行时间已经结束，会调用这个block;
    // SearchVC *sear =[SearchVC sharedSearchVC];
    //  sear.navigationController.tabBarItem.badgeValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"BadgeNumber"];
    
    //  任务结束
    //        [application endBackgroundTask:task];
    //
    //    }];
}

#pragma mark - 程序进入前台
- (void)applicationWillEnterForeground:(UIApplication*)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

#pragma mark - 程序重新激活
- (void)applicationDidBecomeActive:(UIApplication*)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSInteger num = application.applicationIconBadgeNumber;
    int  intNum = (int)num;
    NSLog(@"--->%d", intNum);
    //  [UIApplication sharedApplication].applicationIconBadgeNumber = intNum;
    NSString *numStr = [[NSUserDefaults standardUserDefaults] objectForKey:USER_INFO_Defaults]; //历史保存的
    
    if (intNum != numStr.intValue) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",intNum] forKey:USER_INFO_Defaults];
        
        NSNotification* notif = [NSNotification notificationWithName:BADGE_Num object:self userInfo:nil];
        [[NSNotificationCenter defaultCenter] postNotification:notif];
        
    }
}

#pragma mark - 程序意外终止
- (void)applicationWillTerminate:(UIApplication*)application
{
    // 当应用程序即将终止时调用。如果适当的话，保存数据。 See also applicationDidEnterBackground:.
    // 配合Core Data 使用
    [self saveContext]; //应用程序的托管对象上下文中的更改。
}


// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication*)application didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings {
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    NSString *token =   [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""]
                          stringByReplacingOccurrencesOfString:@">" withString:@""]
                         stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"这里打印的是设备Token:----->%@", token);
    // 百度推送注册 设备Token
    [BPush registerDeviceToken:deviceToken];
    // 阿里白白推送注册 设备Token
    [CloudPushSDK registerDevice:deviceToken];
}



#pragma mark -  此方法是IOS7.0之前的版本使用的推送   -用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(nonnull NSDictionary*)userInfo {
    // 百度-自定义 回调
    [self callMethodPuchApplication:application receiveRemoteNot:userInfo];
    // 阿里
    [CloudPushSDK handleReceiveRemoteNotification:userInfo];
}

#pragma mark -  此方法是IOS7.0之后的版本使用的推送   -用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(nonnull NSDictionary*)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    // 百度-自定义 回调
    [self callMethodPuchApplication:application receiveRemoteNot:userInfo];
    // 阿里
    [CloudPushSDK handleReceiveRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#warning 这里是本地推送。
#pragma mark -  此方法本地的推送
- (void)application:(UIApplication*)application didReceiveLocalNotification:(UILocalNotification*)notification {     // 本地推送
    NSLog(@"接收本地通知啦！！！----》%@", [notification userInfo]);
    TabBarC *tabbarCont = (TabBarC *)self.window.rootViewController;
    NavigationC *navigationCont = (NavigationC *)tabbarCont.viewControllers[0];
    SearchVC * search = navigationCont.viewControllers[0];
    
    if (isJudge == YES) {
        //    NSNotification* notif = [NSNotification notificationWithName:BADGE_Num object:self userInfo:[notification userInfo]];
        //    [[NSNotificationCenter defaultCenter] postNotification:notif];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        }];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication]  cancelLocalNotification:notification];
            
            
            [navigationCont popToRootViewControllerAnimated:YES];
            navigationCont.tabBarController.selectedIndex = 0;
            NSLog(@"%@--->%@",navigationCont.viewControllers, [notification userInfo]);
            [search JumpWithVlue:[notification userInfo]];
            
        }];
        [search addUnreadCount:[notification userInfo]];
        [UtilToolsClss addViewController:self.window.rootViewController withTitleStr:nil withMessage:[[[notification userInfo] objectForKey:@"aps"] objectForKey:@"alert"] withAction:action withOKAction:okAction withStyle:UIAlertControllerStyleAlert];
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        isJudge = NO;
    }else {
        if ([notification userInfo] != nil) {
            [navigationCont popToRootViewControllerAnimated:YES];
            navigationCont.tabBarController.selectedIndex = 0;
            NSLog(@"%@--->%@",navigationCont.viewControllers, [notification userInfo]);
            [search JumpWithVlue:[notification userInfo]];
        }
    }
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    NSLog(@"----->DeviceToken 获取失败，原因：%@", error);
}


/*  ------------------SDK------------*/
#pragma mark - 百度推送
- (void)initBPushSDKWithOptions:(NSDictionary*)launchOptions {
#warning 发布记得改
    // 注册Push --  1.BPushModeProduction - 生产环境   2.BPushModeDevelopment -开发环境
    [BPush registerChannel:launchOptions apiKey:BAIDUPUSHKEY pushMode:BPushModeProduction withFirstAction:NSLocalizedString(@"open", @"打开") withSecondAction:nil withCategory:nil useBehaviorTextInput:false isDebug:NO];
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications]; // 清除全部通知。
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; //角标清0
}

/// 百度 - 推送判断方法
- (void)callMethodPuchApplication:(UIApplication*)application receiveRemoteNot:(nonnull NSDictionary*)userInfo {
    NSString *alertStr = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; //推送的正文
    NSString *badgeStr = [[userInfo objectForKey:@"aps"]  objectForKey:@"badge"];  // 信息条数
    NSLog(@"推送条数--->%@",badgeStr);
    [application setApplicationIconBadgeNumber:[badgeStr integerValue]];
    [[NSUserDefaults standardUserDefaults] setObject:badgeStr forKey:USER_INFO_Defaults];
    
    NSLog(@"%@--->%@",alertStr,badgeStr);
    // 前台 或者 后台开启
    NSLog(@"%ld",(long)[UIApplication sharedApplication].applicationState);
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        
        isJudge = YES;
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.userInfo = userInfo;
        localNotification.soundName = UILocalNotificationDefaultSoundName;//@"SStext.wav"; //
        localNotification.alertBody = userInfo[@"aps"][@"alert"];
        localNotification.fireDate = [NSDate date];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        
        
        
    }else { // 杀死状态--直接跳转 - 不是通知栏
        
        TabBarC *tabbarCont = (TabBarC *)self.window.rootViewController;
        NavigationC *navigationCont = (NavigationC *)tabbarCont.viewControllers[0];
        if(navigationCont.viewControllers.count > 1) {
            [navigationCont popToRootViewControllerAnimated:YES];
        }
        
        if (![navigationCont.tabBarController.selectedViewController isEqual:navigationCont]) {
            navigationCont.tabBarController.selectedIndex = 0;
        }
        
        NSLog(@"%@--->%@",navigationCont.viewControllers,userInfo);
        SearchVC * search = navigationCont.viewControllers[0];
        [search JumpWithVlue:userInfo];
    }
    
    //    [application setApplicationIconBadgeNumber:0]; 不清零
    [BPush handleNotification:userInfo]; //用来给百度推送做统计的
}

- (DeploySDK *)sdk {
    if (!_sdk) {
        _sdk = [[DeploySDK alloc] init];
    }
    return _sdk;
}

/* --------------------------------------------------------------Core Data Stack--------------------------------------------------------------------------*/
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "pp.MyCDDemo" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"PurchaseData" withExtension:@"momd"];
    NSLog(@"------>>%@",modelURL);
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"PurchaseData.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support
- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}
- (void)setManagedObjectContext:(NSManagedObjectContext*)managedObjectContext
{
    _managedObjectContext = managedObjectContext;
    NSDictionary* info = self.managedObjectContext ? @{ DatabaseAvailabilityContext : self.managedObjectContext } : nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:DatabaseAvailabilityNotification object:self userInfo:info];
}


@end
